import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import qs from 'qs'
import { LoadingBar, Modal } from 'view-design'

// views
import Home from '../views/Home.vue'
import PersonalCenter from '../views/PersonalCenter'
import MyMusic from '../views/MyMusic'
import CopyrightSearch from '../views/CopyrightSearch'
import Tasks from '../views/Tasks'
import Transaction from '../views/Transaction'
import Personal from '../views/Personal'
import Cart from '@/views/Cart'
import MyOrder from '@/views/MyOrder'
import LoginRegister from '@/views/LoginRegister'

Vue.use(VueRouter)

const routes = [
  // default
  {
    path: '/',
    name: 'Index',
    component: Home,
    meta: { isLogin: false }
  },
  // no need to login
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { isLogin: false }
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginRegister,
    meta: { isLogin: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: LoginRegister,
    meta: { isLogin: false }
  },
  {
    path: '/copyright_search',
    name: 'Copyright',
    component: CopyrightSearch,
    meta: { isLogin: false }
  },
  {
    path: '/transaction',
    name: 'Transaction',
    component: Transaction,
    meta: { isLogin: false }
  },
  // need to login
  {
    path: '/personal_center',
    name: 'PersonalCenter',
    component: PersonalCenter,
    meta: { isLogin: true }
  },
  {
    path: '/my_music',
    name: 'MyMusic',
    component: MyMusic,
    meta: { isLogin: true }
  },
  {
    path: '/tasks',
    name: 'Tasks',
    component: Tasks,
    meta: { isLogin: true }
  },
  {
    path: '/personal',
    name: 'Personal',
    component: Personal,
    meta: { isLogin: true }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart,
    meta: { isLogin: true }
  },
  {
    path: '/my_order',
    name: 'MyOrder',
    component: MyOrder,
    meta: { isLogin: true }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// check the login permission during route jump
router.beforeEach((to, from, next) => {
  // 用户处于登录状态，直接访问所有页面
  // 但页面用户的数据请求由后端的session进行用户校验
  if (store.state.isLogin === true) {
    next()
  } else {
    // 非登录状态由页面自己的isLogin决定
    const isLogin = qs.parse(sessionStorage.getItem('state')).isLogin === 'true'
    if (to.meta.isLogin && !isLogin) {
      Modal.confirm({
        title: '登录提示',
        content: '点击确定跳转到登录页面',
        onOk: function () {
          LoadingBar.start()
          next({ path: '/login' })
        },
        onCancel: function () {
          return false
        }
      })
    } else {
      // no need to login for user
      next()
    }
  }
})

router.afterEach(route => {
  LoadingBar.finish()
})

export default router
